<template>
	<view class="call-container">
		<view class="user-info">
			<image class="avatar" :src="targetUser.avatar"></image>
			<view class="nickname">{{ targetUser.name || targetUser.id }}</view>
			<view class="status-text">{{ statusText }}</view>
		</view>

		<view class="controls-wrapper">
			<!-- 被叫方显示的按钮 -->
			<view v-if="!isCaller && !isCallAccepted" class="incoming-controls">
				<view class="control-btn reject" @click="onReject">
					<u-icon name="close" color="#fff" size="40"></u-icon>
					<text class="btn-text">拒绝</text>
				</view>
				<view class="control-btn accept" @click="onAccept">
					<u-icon name="phone" color="#fff" size="40"></u-icon>
					<text class="btn-text">接听</text>
				</view>
			</view>

			<!-- 通话中显示的按钮 -->
			<view v-if="isCallAccepted" class="in-call-controls">
				<view class="control-btn small" @click="toggleMute">
					<u-icon :name="isMuted ? 'mic-off' : 'mic'" color="#fff" size="30"></u-icon>
					<text class="btn-text">{{ isMuted ? '取消静音' : '静音' }}</text>
				</view>
				<view class="control-btn reject" @click="onHangup">
					<u-icon name="phone-fill" color="#fff" size="40" style="transform: rotate(135deg);"></u-icon>
				</view>
				<view class="control-btn small" @click="toggleSpeaker">
					<u-icon name="volume" color="#fff" size="30"></u-icon>
					<text class="btn-text">{{ isSpeakerOn ? '听筒' : '免提' }}</text>
				</view>
			</view>

            <!-- 主叫方等待时只显示挂断 -->
            <view v-if="isCaller && !isCallAccepted" class="caller-wait-controls">
                <view class="control-btn reject" @click="onHangup">
					<u-icon name="phone-fill" color="#fff" size="40" style="transform: rotate(135deg);"></u-icon>
				</view>
            </view>
		</view>
	</view>
</template>

<script>
// import AgoraRTC from 'agora-rtc-sdk-ng';
import imService from '@/utils/imService.js';
import { mapState } from 'vuex';

export default {
    data() {
        return {
            rtcClient: null,
            localAudioTrack: null,
            
            // 从页面参数获取
            callParams: null,
            isCaller: false,
            targetUser: {},
            
            // 通话状态
            statusText: '正在呼叫...',
            isCallAccepted: false,
            isMuted: false,
            isSpeakerOn: false,
        };
    },
    computed: {
        ...mapState({
            myUserId: state => state.im.imUserId
        })
    },
    onLoad(options) {
        if (!options.params) {
            this.showErrorAndBack('参数错误');
            return;
        }
        const params = JSON.parse(decodeURIComponent(options.params));
        this.callParams = params;
        this.isCaller = params.isCaller;
        this.targetUser = params.targetUser;
        
        this.statusText = this.isCaller ? '正在等待对方接听...' : '邀请你进行语音通话';
        
        this.setupCallStateListener();

        // 如果是主叫方，直接初始化并加入频道
        if (this.isCaller) {
            this.isCallAccepted = true; // 主叫方直接进入通话中界面（等待状态）
            this.initAndJoinAgora();
        }
    },
    onUnload() {
        this.leaveChannel();
        imService.eventBus.$off('im_call_state_change', this.handleCallStateChange);
    },
    methods: {
        // 接听
        onAccept() {
            imService.answerCall(this.callParams.inviteMessage);
            this.isCallAccepted = true;
            this.statusText = '通话中...';
            this.initAndJoinAgora();
        },
        // 拒绝
        onReject() {
            imService.rejectCall(this.callParams.inviteMessage);
            uni.navigateBack();
        },
        // 挂断
        onHangup() {
            imService.hangupCall(this.targetUser.id);
            this.leaveChannel();
            uni.navigateBack();
        },
        
        // 初始化并加入声网
        async initAndJoinAgora() {
            try {
                this.rtcClient = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' });

                // 监听远端用户发布
                this.rtcClient.on('user-published', async (user, mediaType) => {
                    await this.rtcClient.subscribe(user, mediaType);
                    if (mediaType === 'audio') {
                        user.audioTrack.play();
                    }
                });

                // 加入频道
                await this.rtcClient.join(
                    'YOUR_AGORA_APP_ID', // 替换为你的声网 App ID
                    this.callParams.channelName,
                    this.callParams.agoraToken,
                    this.myUserId
                );
                
                // 创建并发布本地音频
                this.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
                await this.rtcClient.publish([this.localAudioTrack]);
                
                console.log('Agora 加入频道并发布成功');
                this.statusText = '通话中...';

            } catch (error) {
                console.error('Agora 初始化失败:', error);
                this.showErrorAndBack('通话连接失败');
            }
        },

        // 离开频道
        async leaveChannel() {
            if (this.localAudioTrack) {
                this.localAudioTrack.close();
                this.localAudioTrack = null;
            }
            if (this.rtcClient) {
                await this.rtcClient.leave();
                this.rtcClient = null;
            }
            console.log('已离开 Agora 频道');
        },

        // 切换静音
        toggleMute() {
            if (this.localAudioTrack) {
                this.isMuted = !this.isMuted;
                this.localAudioTrack.setEnabled(!this.isMuted);
            }
        },
        // 切换免提 (uni-app 中需要原生插件或特定API)
        toggleSpeaker() {
            // uni-app 切换扬声器/听筒需要特定处理，这里仅做UI切换
            this.isSpeakerOn = !this.isSpeakerOn;
            uni.showToast({ title: `已切换到${this.isSpeakerOn ? '免提' : '听筒'}模式`, icon: 'none' });
            // 实际实现可能需要：
            // plus.audio.setAudioOutputDevice({ device: this.isSpeakerOn ? 'speaker' : 'earpiece' });
        },

        // 设置通话状态监听
        setupCallStateListener() {
            imService.eventBus.$on('im_call_state_change', this.handleCallStateChange);
        },

        handleCallStateChange(callInfo) {
            console.log('通话页面收到状态变更:', callInfo);
            switch (callInfo.state) {
                case 'accepted': // 对方已接听
                    this.statusText = '通话中...';
                    this.isCallAccepted = true;
                    break;
                case 'rejected': // 对方已拒绝
                    this.showErrorAndBack('对方已拒绝');
                    break;
                case 'busy': // 对方忙线
                    this.showErrorAndBack('对方忙线中');
                    break;
                case 'ended': // 对方已挂断
                    this.showErrorAndBack('对方已挂断');
                    break;
            }
        },
        
        showErrorAndBack(title) {
            uni.showToast({ title, icon: 'none', duration: 2000 });
            setTimeout(() => {
                uni.navigateBack();
            }, 2000);
        }
    }
}
</script>

<style scoped>
.call-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #333;
    color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 150rpx 50rpx 100rpx;
    box-sizing: border-box;
}
.user-info {
    text-align: center;
}
.avatar {
    width: 180rpx;
    height: 180rpx;
    border-radius: 50%;
    margin-bottom: 30rpx;
}
.nickname {
    font-size: 40rpx;
    font-weight: bold;
}
.status-text {
    font-size: 28rpx;
    margin-top: 20rpx;
    color: #ccc;
}
.controls-wrapper {
    width: 100%;
}
.incoming-controls, .in-call-controls, .caller-wait-controls {
    display: flex;
    justify-content: space-around;
    align-items: center;
    width: 100%;
}
.control-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 140rpx;
    height: 140rpx;
    border-radius: 50%;
}
.control-btn.small {
    background-color: rgba(255, 255, 255, 0.2);
}
.control-btn.reject {
    background-color: #f74d4d;
}
.control-btn.accept {
    background-color: #04be02;
}
.btn-text {
    font-size: 24rpx;
    margin-top: 10rpx;
}
</style>